package com.wzt.gift.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wzt.gift.asserts.Assert;
import com.wzt.gift.clients.UserClient;
import com.wzt.gift.domain.LoginUser;
import com.wzt.gift.domain.Permission;
import com.wzt.gift.enums.ResponseEnum;
import com.wzt.gift.holder.LoginUserContextInfo;
import com.wzt.gift.mapper.LoginUserMapper;
import com.wzt.gift.mapper.PermissionMapper;
import com.wzt.gift.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author Zenith
 * @Date 2022/10/17 18:48
 * @Version 1.0
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserClient userClient;


    /**
     * 从数据库查询对应用户名的密码和所有权限
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        EntityWrapper<LoginUser> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username)
                .or()
                .eq("tel", username)
                .or()
                .eq("email", username);
        // 用户登录，从数据库中查询是否存在该用户
        List<LoginUser> loginUsers = loginUserMapper.selectList(wrapper);
        // 断言用户存在
        Assert.listIsNotEmpty(loginUsers, ResponseEnum.CODE_USER_NOT_EXIST);


        LoginUser loginUser = loginUsers.get(0);
        // 登录用户上下文
        LoginUserContextInfo userContextInfo = new LoginUserContextInfo();
        // 设置登录用户id和名字
        userContextInfo.setLoginUserId(loginUser.getId());
        userContextInfo.setLoginUserName(loginUser.getUsername());
        // 获取用户密码和权限
        String password = loginUser.getPassword();
        // 用户的权限列表
        Collection<GrantedAuthority> authorities = new ArrayList<>();

        // 登录用户类型为0说明是管理员，1为普通用户
        if (loginUser.getType() == 0) {
            // 为管理员添加权限
            List<Permission> permissions = permissionMapper.selectPermissionsByUserId(loginUser.getId());
            permissions.forEach(permission -> {
                authorities.add(new SimpleGrantedAuthority(permission.getSn()));
            });
        } else {
            // 调用用户服务，根据登录用户id查询用户基本信息
            AjaxResult ajaxResult = userClient.getByLoginId(loginUser.getId());
            if (ajaxResult.isSuccess()) {
                com.wzt.gift.domain.User user = (com.wzt.gift.domain.User) ajaxResult.getResultObj();
                userContextInfo.setUserId(user.getId());
                userContextInfo.setUsername(user.getUsername());
            }
        }

        User user = new User(JSON.toJSONString(userContextInfo), password, authorities);
        return user;
    }
}
